from django.shortcuts import render, HttpResponse
from rest_framework.viewsets import ViewSet, GenericViewSet, ModelViewSet
from rest_framework.views import APIView
from . import serializer
from Cinematography.utils.response import APIResponse
from rest_framework.decorators import action
from . import models
import re
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin
from Cinematography.libs.tx_sms import get_code, send_message
from django.core.cache import cache
from django.conf import settings
from Cinematography.apps.user import thorttlings


class LoginView(ViewSet):
    @action(methods=('POST',), detail=False)
    def login(self, request, *args, **kwargs):
        ser = serializer.UserSerilaizer(data=request.data)
        print(1111)
        if ser.is_valid():
            print(2222)
            token = ser.context['token']
            # ser.context['user'] 是user对象
            username = ser.context['user'].username
            id = ser.context['user'].id
            # {'code':1
            #  msg:'chengg'
            #  token:'sdfasdf'
            #  username:'root'
            #  }
            return APIResponse(token=token, username=username, id=id, )
        else:
            return APIResponse(code=0, msg=ser.errors)

    @action(methods=('GET',), detail=False)
    def check_telephone(self, request, *args, **kwargs):
        import re
        # query_params就是query dic 可以取到get请求传过来的参数
        telephone = request.query_params.get('telephone')
        # print(telephone)
        if not re.match('^1[3-9][0-9]{9}$', telephone):
            return APIResponse(code=0, msg='手机号不合法')
        try:
            models.User.objects.get(telephone=telephone)
            return APIResponse(code=1, msg='手机号验证成功')
        except:
            return APIResponse(code=0, msg='手机号不存在')

    @action(methods=['POST'], detail=False)
    def code_login(self, request, *args, **kwargs):
        ser = serializer.CodeUserSerilaizer(data=request.data)
        if ser.is_valid():
            token = ser.context['token']
            username = ser.context['user'].username
            return APIResponse(token, username=username)
        else:
            return APIResponse(code=0, msg=ser.errors)


class SendSmSView(ViewSet):
    throttle_classes = [thorttlings.SMSThrotting, ]

    @action(methods=['GET'], detail=False)
    def send(self, request, *args, **kwargs):
        print(111111111111111111111111111111111)
        # get请求没有data，只能从query_params中拿数据，或者GET.get（telephone）
        telephone = request.query_params.get('telephone')
        print(type(telephone))
        user1 = models.User.objects.filter(telephone=telephone).first()
        if not re.match('^1[3-9][0-9]{9}$', telephone):
            return APIResponse(code=0, msg='手机号不合法')
        elif user1:
            return APIResponse(code=0, msg='手机号以注册')
        code = get_code()
        result = send_message(telephone, code)
        # 验证码保存(保存到哪)
        # sms_cache_%s
        cache.set(settings.PHONE_CACHE_KEY % telephone, code, 180)
        if result:
            return APIResponse(code=1, msg='验证码发送成功')
        else:
            return APIResponse(code=0, msg='验证码发送失败')


class RegisterView(GenericViewSet, CreateModelMixin):
    queryset = models.User.objects.all()
    serializer_class = serializer.UserRegisterSerilaizer

    # 一般我们自己会这样写
    def create(self, request, *args, **kwargs):
        print(request.data)
        ser = self.get_serializer(data=request.data)
        if ser.is_valid():
            ser.save()  # 调用序列化类的create方法
            return APIResponse(code=1, msg='注册成功', username=ser.data.get('username'),
                               id=cache.get(ser.data.get('telephone')))
        else:
            print(ser.errors)
            return APIResponse(code=0, msg=ser.errors)

    # 具体执行流程，忘记了
    # def create(self, request, *args, **kwargs):
    #     response = super().create(request,*args,**kwargs)
    #     username = response.data.get('username')
    #     return APIResponse(code=1,msg='注册成功',username=username)


# class ModifyInfo(GenericViewSet,UpdateModelMixin):
#     queryset = models.User.objects.all()
#     serializer_class = serializer.CreateUserSerializer
#
#     def update(self,request, *args, **kwargs):
#         ser=self.get_serializer(data=request.data)
#


# def create(self, request, *args, **kwargs):
#     ser = self.get_serializer(data=request.data)
#     if ser.is_valid():
#         return APIResponse(code=1,msg='修改成功')
#     else:
#         return APIResponse(code=0,msg=ser.errors)

# 这个是最原始的
# class ModifyInfo(GenericViewSet,UpdateModelMixin):
#     queryset = models.User.objects.all()
#     serializer_class = serializer.CreateUserSerializer
#
#     def update(self, request, *args, **kwargs):
#         ser = self.get_serializer(data=request.data)
#         print(request.data)
#         if ser.is_valid():
#             ser.save()
#             return APIResponse(code=1, msg='修改成功',)
#         else:
#             print(ser.errors)
#             return APIResponse(code=0, msg=ser.errors)


# 这种直接可以保存，调用super().update()调用UpdateModelMixin中的update。
class ModifyInfo(GenericViewSet, UpdateModelMixin):
    queryset = models.User.objects.all()
    serializer_class = serializer.CreateUserSerializer

    def update(self, request, *args, **kwargs):
        print(request.data)
        user = models.User.objects.filter(telephone=request.data['telephone']).first()
        ser = self.get_serializer(instance=user, data=request.data)
        print(ser, 111)
        if ser.is_valid():
            ser.save()
            return APIResponse(code=1, msg='修改成功', )
        else:
            print(ser.errors)
            return APIResponse(code=0, msg=ser.errors)
        # res = super().update(request, *args, **kwargs)
        # # ser = self.get_serializer(data=request.data)
        # print(res)
        # return APIResponse(code=1, msg=res)


# django 里面上传文件默认只处理单个文件上传，批量上传的时候request.FILES 的类型为 MultiValueDict，这种字典类是特殊定义的，要取得list 需要调用 getlist  方法:
# 图片
import os


class Image(ModelViewSet):
    queryset = models.Image.objects.all()
    serializer_class = serializer.CreateImageSerializer

    def create(self, request, *args, **kwargs):
        files = request.FILES.getlist('files')
        image_path = []
        for file in files:
            path = os.path.join('Cinematography', 'media', 'photo', file.name)
            with open(path, 'wb') as f:
                for line in file:
                    f.write(line)
                image_path.append(path)
        print(image_path, type(image_path), 999)

        return APIResponse(code=1, msg=image_path)
        # ser = self.get_serializer(data=image_path)
        # ser.is_valid(raise_exception=True)
        # return APIResponse(code=1,msg=image_path)
        # print(ser, 111)
        # self.perform_create(ser)
        # if ser.is_valid():
        #     ser.save()  #调用序列化类的create方法
        #     return APIResponse(code=1,msg='成功')
        # else:
        #     print(ser.errors)
        #     return APIResponse(code=0, msg=ser.errors)
    # def perform_create(self, serializer):
    #     serializer.save()


from rest_framework.generics import GenericAPIView
import time


class Yuepai(ModelViewSet):
    queryset = models.Appointment.objects.all()
    serializer_class = serializer.CreateAppointmentSerializer
    print(0000)

    def create(self, request, *args, **kwargs):
        print(11111)
        # print(request.POST.get('fieldname'))
        # print(request.data.get('fieldname'))
        print(1111)
        print(request.data)
        uid = request.data.pop('uid')
        # time1=request.data.pop('apTime')
        # time2=time.localtime(time1)
        # print(time2)
        # apTime=time.strftime('%Y-%m-%d',time2)
        # print(apTime,000)
        # request.data['apTime'] = apTime
        # user=models.User.objects.filter(id=user1)
        # user=str(user)
        request.data['user'] = uid
        print(request.data['pictureurl'])
        # print(request.data,222)
        ser = self.get_serializer(data=request.data)
        print(ser)
        print(2222)
        # print(ser.data)
        if ser.is_valid():
            ser.save()  # 调用序列化类的create方法
            return APIResponse(code=1)
        print(ser.errors, '报错信息')
        return APIResponse(code=0)


class Works(ModelViewSet):
    queryset = models.Appointment.objects.all()
    serializer_class = serializer.CreateArticleSerializer

    def create(self, request, *args, **kwargs):
        uid = request.data.pop('uid')
        request.data['user'] = uid
        ser = self.get_serializer(data=request.data)
        print(request.data)
        if ser.is_valid():
            ser.save()  # 调用序列化类的create方法
            return APIResponse(code=1)
        print(ser.errors, '报错信息')
        return APIResponse(code=0)


# 场地
class Venue(ModelViewSet):
    queryset = models.Venue.objects.all()
    serializer_class = serializer.CreateVenueSerializer

    def create(self, request, *args, **kwargs):
        uid = request.data.pop('uid')
        request.data['user'] = uid
        ser = self.get_serializer(data=request.data)
        print(request.data)
        if ser.is_valid():
            ser.save()  # 调用序列化类的create方法
            return APIResponse(code=1)
        print(ser.errors, '报错信息')
        return APIResponse(code=0)


# 教程
class Tutorial(ModelViewSet):
    queryset = models.Venue.objects.all()
    serializer_class = serializer.CreateTutorialSerializer

    def create(self, request, *args, **kwargs):
        uid = request.data.pop('uid')
        request.data['user'] = uid
        ser = self.get_serializer(data=request.data)
        print(request.data)
        if ser.is_valid():
            ser.save()  # 调用序列化类的create方法
            return APIResponse(code=1)
        print(ser.errors, '报错信息')
        return APIResponse(code=0)
